import { defineStore } from 'pinia'
import { ref, computed, watch } from 'vue'
import type { GlobalThemeOverrides } from 'naive-ui'
import { darkTheme } from 'naive-ui'

export type ThemeMode = 'light' | 'dark' | 'auto'

export const useThemeStore = defineStore('theme', () => {
  // 主题模式
  const themeMode = ref<ThemeMode>('auto')

  // 系统主题（通过媒体查询检测）
  const systemTheme = ref<'light' | 'dark'>('light')

  // 计算实际使用的主题
  const actualTheme = computed(() => {
    if (themeMode.value === 'auto') {
      return systemTheme.value
    }
    return themeMode.value
  })

  // Naive UI 主题对象（dark 时使用 darkTheme，light 时为 null）
  const naiveTheme = computed(() => {
    return actualTheme.value === 'dark' ? darkTheme : null
  })

  // 主题覆盖配置（可选，用于自定义主题色）
  const themeOverrides = computed<GlobalThemeOverrides>(() => {
    return {
      common: {
        primaryColor: '#18a058',
        primaryColorHover: '#36ad6a',
        primaryColorPressed: '#0c7a43',
        primaryColorSuppl: '#36ad6a'
      }
    }
  })

  // 初始化系统主题检测
  const initSystemThemeDetection = (): void => {
    // 检测系统主题偏好
    const darkModeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
    systemTheme.value = darkModeMediaQuery.matches ? 'dark' : 'light'

    // 监听系统主题变化
    darkModeMediaQuery.addEventListener('change', (e) => {
      systemTheme.value = e.matches ? 'dark' : 'light'
    })
  }

  // 设置主题模式
  const setThemeMode = async (mode: ThemeMode): Promise<void> => {
    themeMode.value = mode
    // 持久化到配置
    try {
      const settings = (await window.api.getAppConfig('settings')) as { theme?: ThemeMode } | null
      await window.api.saveAppConfig('settings', { ...settings, theme: mode })
    } catch (error) {
      console.error('保存主题配置失败:', error)
    }
  }

  // 从配置加载主题
  const loadThemeFromConfig = async (): Promise<void> => {
    try {
      const settings = (await window.api.getAppConfig('settings')) as { theme?: ThemeMode }
      if (settings && settings.theme) {
        themeMode.value = settings.theme
      }
    } catch (error) {
      console.error('加载主题配置失败:', error)
    }
  }

  // 监听主题变化，应用到 HTML 根元素
  watch(
    actualTheme,
    (theme) => {
      document.documentElement.setAttribute('data-theme', theme)
      // 同时设置 class 方便 CSS 使用
      if (theme === 'dark') {
        document.documentElement.classList.add('dark')
        document.documentElement.classList.remove('light')
      } else {
        document.documentElement.classList.add('light')
        document.documentElement.classList.remove('dark')
      }
    },
    { immediate: true }
  )

  return {
    themeMode,
    systemTheme,
    actualTheme,
    naiveTheme,
    themeOverrides,
    setThemeMode,
    initSystemThemeDetection,
    loadThemeFromConfig
  }
})
